package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import db.DBUtil;
import model.Selection;

public class SelectionDAO {
	public boolean addSelection(Selection selection){
		try{
			Connection conn = DBUtil.getConnection();
			PreparedStatement stmt = conn.prepareStatement("insert into selections (topicid,selectionname,ordername) values (?,?,?)");
			stmt.setInt(1, selection.getTopicId());
			stmt.setString(2, selection.getName());
			stmt.setString(3, selection.getOrderName());
			stmt.execute();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	public List<Selection> getSelectionsByTopicId(int topicId){
		List<Selection> list = new ArrayList<Selection>();
		try{
			Connection conn = DBUtil.getConnection();
			PreparedStatement stmt = conn.prepareStatement("select * from selections where topicid=?");
			stmt.setInt(1, topicId);
			ResultSet rs = stmt.executeQuery();
			while(rs.next()){
				Selection s = new Selection(rs.getInt("id"), rs.getInt("topicid"), rs.getString("selectionname"), rs.getString("ordername"));
				list.add(s);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}
	
	public boolean deleteByTopicId(int topicId){
		try{
			Connection conn = DBUtil.getConnection();
			PreparedStatement stmt = conn.prepareStatement("delete from selections where topicid=?");
			stmt.setInt(1, topicId);
			stmt.execute();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	public boolean updateSelection(Selection selection) {
		try{
			Connection conn = DBUtil.getConnection();
			PreparedStatement stmt = conn.prepareStatement("update selections set id=?,topicid=?,selectionname=?,ordername=? where id=?");
			stmt.setInt(1, selection.getId());
			stmt.setInt(2, selection.getTopicId());
			stmt.setString(3, selection.getName());
			stmt.setString(4, selection.getOrderName());
			stmt.setInt(5, selection.getId());
			stmt.execute();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
}
